package peer.dstdb.message;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;

import peer.Config;
import peer.Message;
import peer.share.CacheFileInfo;
import peer.tools.ByteIntSwitch;
import peer.tools.ByteShortSwitch;

public class CastAddMessage extends Message{
	public short sType=peer.tools.MessageType.sType_DB_CastAddMessage;
	int sourceSessionId=0;
	byte[] dpData=null;
	byte[] md=null;
	short blockNum;
	InetAddress assistNodeIp;
	int assistNodePort;
	int assistSessionId;
	CacheFileInfo bi;
	byte[] biByte;
	InetAddress lanIp;
	public CastAddMessage(byte[] md,int sourceSessionId,CacheFileInfo bi){
		dpData=new byte[42+bi.getByte().length];
		this.md=md;
		this.sourceSessionId=sourceSessionId;
		ByteShortSwitch.toByteArray(ver, dpData, 0);  //add: ver
		ByteShortSwitch.toByteArray(sType, dpData, 2);  //add: service type
		System.arraycopy(md, 0, dpData, 4,16);  //md
		ByteIntSwitch.toByteArray(sourceSessionId, dpData, 20);  //add: sessionId
		System.arraycopy(Config.assistNodeIp.getAddress(), 0, dpData, 24, 4); 
		ByteIntSwitch.toByteArray(Config.assistNodePort, dpData, 28);
		ByteIntSwitch.toByteArray(Config.assistSessionId, dpData, 32);
		System.arraycopy(peer.Config.lanIp.getAddress(), 0, dpData, 36, 4);
		
		ByteShortSwitch.toByteArray((short) bi.getByte().length, dpData, 40); //bi length
		System.arraycopy(bi.getByte(), 0, dpData, 42, bi.getByte().length); // bi
		dp=new DatagramPacket(dpData,dpData.length);
	}
	
	public InetAddress getLanIp(){
		return lanIp;
	}
	
	public int getSourceSessionId (){
		return sourceSessionId ;
	}
	
	public byte[] getMd(){
		return md;
	}
	
	public CacheFileInfo getBlockInfo(){
		return bi;
	}
	
	
	public InetAddress getAssistNodeIp(){
		return assistNodeIp;
	}
	
	public int getAssistNodePort(){
		return assistNodePort;
	}
	
	public int getAssistSessionId(){
		return assistSessionId;
	}
	
	public CastAddMessage(DatagramPacket dp){
		this.dp=dp;
		dpData=dp.getData();
		ver=ByteShortSwitch.toShort(dpData, 0);
		sType=ByteShortSwitch.toShort(dpData, 2);
		
		md=new byte[16];
		System.arraycopy(dpData, 4, md, 0, 16);
		sourceSessionId=ByteIntSwitch.toInt(dpData, 20);
		
		byte[] b=new byte[4];
		System.arraycopy(dpData, 24, b, 0, 4);
		try {
			assistNodeIp=InetAddress.getByAddress(b);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		assistNodePort=ByteIntSwitch.toInt(dpData, 28);
		assistSessionId=ByteIntSwitch.toInt(dpData, 32);
		byte[] b2=new byte[4];
		System.arraycopy(dpData, 36, b2, 0, 4);
		try {
			lanIp=InetAddress.getByAddress(b2);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		short biLength=ByteShortSwitch.toShort(dpData, 40);
		biByte=new byte[biLength];
		System.arraycopy(dpData, 42, biByte, 0, biLength);
		bi=new CacheFileInfo(biByte);
	}
}
